package api

import (
	"fmt"
	util "mall/pkg/utils"
	"mall/service"
	"net/http"

	"github.com/gin-gonic/gin"
)

//用户登陆操作
func UserRegister(c *gin.Context) {
	//创建一个UserRegisterService对象
	var userRegisterService service.UserRegisterService
	//将请求中的数据绑定到UserRegisterService中
	if err := c.ShouldBind(&userRegisterService); err == nil {
		//调用这个对象中的Register方法
		res := userRegisterService.Register()
		c.JSON(http.StatusOK, res)
	} else {
		c.JSON(400, ErrorResponse(err))
		util.Logger().Infoln(err)
	}
}

//UserLogin 用户登陆接口
func UserLogin(c *gin.Context) {
	var userLoginService service.UserLoginService
	if err := c.ShouldBind(&userLoginService); err == nil {
		res := userLoginService.Login()
		c.JSON(200, res)
	} else {
		c.JSON(400, ErrorResponse(err))
		util.Logger().Infoln(err)
	}
}

//用户更改昵称
func UserUpdate(c *gin.Context) {
	var userUpdateService service.UserUpdateService
	claims, _ := util.ParseToken(c.GetHeader("Authorization"))
	if err := c.ShouldBind(&userUpdateService); err == nil {
		res := userUpdateService.Update(claims.ID)

		c.JSON(200, res)
	} else {
		c.JSON(400, ErrorResponse(err))
		util.Logger().Infoln(err)
	}
}

//用户上传头像
func UploadAvatar(c *gin.Context) {
	fmt.Println("112")
	file, fileHeader, err := c.Request.FormFile("file")
	if err != nil {
		c.JSON(400, ErrorResponse(err))
	}
	fmt.Println("113")
	fileSize := fileHeader.Size
	fmt.Println("111")
	uploadAvatarService := service.UploadAvatarService{}
	chaim, _ := util.ParseToken(c.GetHeader("Authorization"))
	if err := c.ShouldBind(&uploadAvatarService); err == nil {
		fmt.Print(chaim.ID, file, fileSize)
		res := uploadAvatarService.Post(chaim.ID, file, fileSize)
		c.JSON(200, res)
	} else {
		c.JSON(400, ErrorResponse(err))
		util.Logger().Infoln(err)
	}
}

//发送邮箱
func SendEmail(c *gin.Context) {
	var sendEmailService service.SendEmailService
	chaim, _ := util.ParseToken(c.GetHeader("Authorization"))
	if err := c.ShouldBind(&sendEmailService); err == nil {
		res := sendEmailService.Send(chaim.ID)
		c.JSON(200, res)
	} else {
		c.JSON(400, ErrorResponse(err))
		util.Logger().Infoln(err)
	}
}

//验证邮箱
func ValidEmail(c *gin.Context) {
	var vaildEmailService service.ValidEmailService
	if err := c.ShouldBind(vaildEmailService); err == nil {
		res := vaildEmailService.Valid(c.GetHeader("Authorization"))
		c.JSON(200, res)
	} else {
		c.JSON(400, ErrorResponse(err))
		util.Logger().Infoln(err)
	}
}
